<?php

namespace App\Http\Controllers\Business;

use App\Http\Util\Tool;
use App\Model\Device;
use App\Model\House;
use App\Model\Menus;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class HouseController extends Controller
{


    /**创建房源
     * @return \Illuminate\Http\JsonResponse
     */
    public function create()
    {
        try {
            $data = request()->post();
            if (!array_key_exists('id', $data) || $data['id'] <= 0) {
                $house = new House();
            } else {
                $house = House::where('id',$data['id'])->first();
            }
            $house->business_id = $this->getBusinessId();
            $house->name = $data['house_name'];
            $house->province = $data['province'];
            $house->city = $data['city'];
            $house->district = $data['district'];
            $house->estate_name = $data['estate_name'];
            $house->fang = $data['house_fang'];
            $house->ting = $data['house_ting'];
            $house->chu = $data['house_chu'];
            $house->wei = $data['house_wei'];
            $house->size = $data['size'];
            $house->rent = $data['rent'];
            $house->deposit_num = $data['deposit_num'];
            $house->rent_num = $data['rent_num'];
            $house->save();
            Device::query()->where('house_id',$house->id)->update(['house_id'=>0]);
            if($data['device_id']){
                Device::query()->where('id',$data['device_id'])->update(['house_id'=>$house->id]);
            }
            return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => $data]);
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => $e->getMessage()]);
        }
    }

    /**删除房源
     * @return \Illuminate\Http\JsonResponse
     */
    public function del()
    {
        try {
            $id = request()->get('id');
            $house = House::where('id', $id)->first();
            if($house->device_id){
                return response()->json(['code' => 1001, 'msg' => '请先解绑相关设备']);
            }
            if ($house->delete()) {
                return response()->json(['code' => 200, 'msg' => '删除成功']);
            }
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => '操作繁忙 请稍后再试']);
        }
    }


}
